package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.core.proxy.model.GoodsServiceChargeItem;
import com.lsh.oms.core.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author peter
 * @date 18/8/26
 */
@Service
public class WgServiceProxy {
    private final Logger logger = LoggerFactory.getLogger(WgServiceProxy.class);

    private static final String WG_URI_GOOD_WEIGHT = "/api/goodsinfo/getList";
    private static final String WG_URI_GOOD_SERVICE_CHARGE = "/api/goods/getGoodsServiceCharge";

    private static final String WG_URI_PO_SO_PSI = "/api/purchaseorder/poAndSoTransfer";


    @Value("${psi.bj.path}")
    private String psiBjPath;

    /**
     * 查询商品重量
     *
     * @param supplyCodes
     * @param ownerId
     * @return
     */
    public Map<String, BigDecimal> getGoodsWeight(String supplyCodes, String ownerId, Long venderId) {
        Map<String, BigDecimal> goodsWeight = new HashMap<>();
        String uri = psiBjPath + WG_URI_GOOD_WEIGHT;
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("goods_ids", supplyCodes);
        contentMap.put("owner_id", ownerId);

        String content = JSON.toJSONString(contentMap);
        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI=" + uri + "][Request:" + content + "]");
        CommonResult<String> result = HttpUtils.post(uri, entity, false, this.buildHeaders(venderId));
        logger.info("[POST][URI=" + uri + "][Response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        Integer ret = json.getInteger("ret");
        //成功
        if (Integer.valueOf(0).equals(ret)) {
            JSONObject body = JSONObject.parseObject(json.getString("content"));
            JSONArray goodsArray = body.getJSONArray("list");

            for (int i = 0; i < goodsArray.size(); i++) {
                JSONObject good = (JSONObject) goodsArray.get(i);
                goodsWeight.put(good.getString("goods_id"), good.getBigDecimal("third_pack_weight"));
            }
        } else {
            throw new BusinessException(CommonResult.ERROR, json.getString("msg"));
        }
        return goodsWeight;
    }

    /**
     * 查询商品服务费、税率等信息
     *
     * @param supplyCodes
     * @param ownerId
     * @return
     */
    public List<GoodsServiceChargeItem> getGoodsServiceCharge(Set<String> supplyCodes, String ownerId, Long venderId) {
        String uri = psiBjPath + WG_URI_GOOD_SERVICE_CHARGE;
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("goods_id", supplyCodes);
        contentMap.put("owner_id", ownerId);

        String content = JSON.toJSONString(contentMap);
        StringEntity entity = new StringEntity(content, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());

        logger.info("[POST][URI=" + uri + "][Request:" + content + "]");
        CommonResult<String> result = HttpUtils.post(uri, entity, false, this.buildHeaders(venderId));
        logger.info("[POST][URI=" + uri + "][Response:" + JSON.toJSONString(result) + "]");

        if (!CommonResult.SUCCESS.equals(result.getCode())) {
            throw new BusinessException(CommonResult.ERROR, result.getMessage());
        }

        String data = result.getData();
        JSONObject json = JSONObject.parseObject(data);
        Integer ret = json.getInteger("ret");
        //成功
        if (Integer.valueOf(0).equals(ret)) {
            String respContent = json.getString("content");
            if (StringUtils.isNotEmpty(respContent)) {
                return JSON.parseArray(respContent, GoodsServiceChargeItem.class);
            }
        } else {
            throw new BusinessException(CommonResult.ERROR, json.getString("msg"));
        }
        return Collections.emptyList();
    }

    private Header[] buildHeaders(Long venderId) {
        Header[] headers = {new BasicHeader("Content-Type", "application/json"),
                new BasicHeader("VENDERID", venderId + ""),};
        return headers;
    }

    /**
     * 查询商品服务费、税率等信息
     *
     * @param contentJson
     * @param venderId
     * @return
     */
    public Integer pushPoSo(JSONObject contentJson, Long venderId) {
        String uri = psiBjPath + WG_URI_PO_SO_PSI;

        try {
            String content = contentJson.toJSONString();
            StringEntity entity = new StringEntity(content, Consts.UTF_8);
            entity.setContentType(ContentType.APPLICATION_JSON.toString());

            logger.info("[POST][URI=" + uri + "][Request:" + content + "]");
            CommonResult<String> result = HttpUtils.post(uri, entity, false, this.buildHeaders(venderId));
            logger.info("[POST][URI=" + uri + "][Response:" + JSON.toJSONString(result) + "]");

            if (!CommonResult.SUCCESS.equals(result.getCode())) {
                throw new BusinessException(CommonResult.ERROR, result.getMessage());
            }

            String data = result.getData();
            JSONObject json = JSONObject.parseObject(data);
            Integer ret = json.getInteger("ret");
            //成功
            if (Integer.valueOf(0).equals(ret)) {
                return 1;
            } else {
                return -1;
            }
        } catch (BusinessException e) {
            logger.error("psi 异常",e);
        }

        return -1;
    }


}
